<template>
  <pageTabelLayout>
    <template #pageHeader>
      <div class="search-form divClass" v-if="headerShow" style="margin-top: 15px">
        <div>
          <a-form size="small" :model="pageData" layout="inline" label-col-flex="80px">
            <CorporateSectorCascader
              :configCascader="configCascader"
              @changeCascader="firmChange"
            />
            <a-form-item label="仓库" required label-col-flex="80px">
              <a-select
                popup-container="html"
                class="bacClass"
                :style="{ width: '214px' }"
                v-model="pageData.warehouseId"
                allow-search
              >
                <a-option v-for="item in fhWhList" :value="item.id">
                  {{ item.warehouseName }}
                </a-option>
              </a-select>
            </a-form-item>
            <a-form-item label="物料大类" label-col-flex="80px">
              <a-select
                popup-container="html"
                :style="{ width: '200px' }"
                class="bacClass"
                v-model="pageData.majorCategory"
                @change="bigChange(1)"
                :filter-option="false"
                allow-search
                allow-clear
                @focus="WLfocusSel(1)"
              >
                <a-option v-for="item in pageData.bigList" :key="item.id">
                  {{ item.bigClassName }}
                </a-option>
              </a-select>
            </a-form-item>
            <a-form-item label="物料中类" label-col-flex="80px">
              <a-select
                popup-container="html"
                :style="{ width: '200px' }"
                class="bacClass"
                :disabled="!pageData.majorCategory"
                v-model="pageData.middleCategory"
                @change="bigChange(2)"
                :filter-option="false"
                allow-search
                allow-clear
                @focus="WLfocusSel(2)"
              >
                <a-option v-for="item in pageData.middleList" :key="item.id">
                  {{ item.middleClassName }}
                </a-option>
              </a-select>
            </a-form-item>
            <a-form-item label="物料小类" label-col-flex="80px">
              <a-select
                popup-container="html"
                :style="{ width: '200px' }"
                class="bacClass"
                :disabled="!pageData.middleCategory"
                v-model="pageData.subCategory"
                :filter-option="false"
                allow-search
                allow-clear
                @focus="WLfocusSel(3)"
              >
                <a-option v-for="item in pageData.smallList" :key="item.id">
                  {{ item.subClassName }}
                </a-option>
              </a-select>
            </a-form-item>
            <a-form-item label="物料编号" label-col-flex="80px">
              <a-input
                :style="{ width: '200px' }"
                class="bacClass"
                v-model="pageData.materialCode"
                allow-clear
              ></a-input>
            </a-form-item>
            <a-form-item label="物料名称" label-col-flex="80px">
              <a-input
                :style="{ width: '200px' }"
                class="bacClass"
                v-model="pageData.materialName"
                allow-clear
              ></a-input>
            </a-form-item>
          </a-form>
        </div>
      </div>
      <div class="my-divisders">
        <a-divider orientation="center">
          <icon-double-up
            v-if="headerShow"
            @click="headerShow = false"
            :strokeWidth="2"
            :size="18"
          />
          <icon-double-down v-else @click="headerShow = true" :strokeWidth="2" :size="18" />
        </a-divider>
      </div>
      <div class="my-tool-bar">
        <Toolbar :items="pageData.btnList" @select="selectHandler" @export="exports" @fhzy="fhzy">
        </Toolbar>
      </div>
    </template>
    <template #pageTabel>
      <a-spin
        :loading="pageData.pageLoading"
        tip="加载中"
        dot
        style="height: 100%; width: 100%; z-index: 999"
      >
        <AgGridVuesCopys
          :rowHeight="33"
          :headerHeight="33"
          rowSelection="multiple"
          @grid-ready="gridReady"
          style="height: 100%"
          :defaultColDef="defaultColDef"
          :suppressCopyRowsToClipboard="true"
          class="ag-theme-alpine"
          :rowData="table.dataList"
          :columnDefs="tc"
          :localeText="localeText1"
        >
        </AgGridVuesCopys>
      </a-spin>
    </template>
    <paginationCopys
      :page-size-options="pagingList1"
      :total="total"
      :page-size="size"
      :current="page"
      show-total
      show-jumper
      show-page-size
      @change="PageSize"
      @page-size-change="change1"
      style="justify-content: center"
    />
  </pageTabelLayout>
</template>

<script lang="ts">
  import { post, get } from '@/api/http'
  import {
    useTable,
    useRowKey,
    useTableColumn,
    usePagination,
    useRowSelection,
  } from '@/hooks/table'
  import emitter from '@/hooks/useEventBus'
  import { ref, reactive, onMounted, toRefs } from 'vue'
  import Toolbar from '@/components/Toolbar.vue'
  import { Button, Form, Message, Modal } from '@arco-design/web-vue'
  import { FormInstance } from '@arco-design/web-vue/es/form'
  import { baseURL } from '../../api/axios.config'
  import axios from 'axios'
  import filedownload from 'js-file-download'
  import usePermission from '@/store/modules/permission'
  import PageTabelLayout from '@/components/pageTabelLayout.vue'
  import MyTable from '@/components/MyTable'
  import ButtonRenderer from '@/components/TableCellRenderer/ButtonRenderer'
  import { template } from 'lodash'
  import { setupGlobalComponent } from '@/layouts'
  import { localeText } from '@/api/aggridZw'
  // 引入
  
  import { stringify } from 'qs'
  import { pagingList } from '@/api/paging'
  import WHService from '@/service/wh'
  import CorporateSectorCascader from '@/components/corporateSectorCascader/inde.vue'
  import { saveOrUpdateGridState as saveOrUpdateGridState01 } from '@/hooks/useGridState'
  interface BrandInfo {
    id: any
    brandCode: string
    brandName: string
    clothClass: string
    remark: string
    deleteState: number | string
    createName: string
    createTime: string
    updateName: string
    updateTime: string
  }

  export default {
    name: 'HardwareWarehouseMonthReport',

    setup(props: any, { emit }) {
      const total = ref(0)
      const page = ref(1)
      const size = ref(10)
      function PageSize(val: any) {
        page.value = val
        doRefresh()
      }
      function change1(val: any) {
        size.value = val
        doRefresh()
      }
      const headerShow = ref<boolean>(true)
      function doRefresh() {
        if (pageData.firmId == '' || pageData.firmId == null) {
          Message.error('工厂必填！')
          return
        }
        if (pageData.warehouseId == '' || pageData.warehouseId == null) {
          Message.error('仓库必填！')
          return
        }
        if (
          pageData.majorCategory ||
          pageData.middleCategory ||
          pageData.subCategory ||
          pageData.materialCode ||
          pageData.materialName
        ) {
          page.value = 1
        }
        pageData.pageLoading = true
        post({
          url: '/wms/ironwareStockSummary/findIronwareStockDaily',
          data: {
            page: page.value,
            size: size.value,
            firmId: pageData.firmId,
            warehouseId: pageData.warehouseId,
            majorCategory: pageData.majorCategory,
            middleCategory: pageData.middleCategory,
            subCategory: pageData.subCategory,
            materialCode: pageData.materialCode,
            materialName: pageData.materialName,
          },
        })
          .then(({ data, code }: any) => {
            if (code === 200) {
              table.handleSuccess(data.records)
              // 查询方法改
              gridOption.value.setRowData(data.records)
              total.value = data.total
            }
          })
          .catch(console.log)
          .finally(() => {
            pageData.pageLoading = false
          })
      }

      const pagination = usePagination(doRefresh)
      const table = useTable()
      const rowKey = useRowKey('id')
      const tableColumns = useTableColumn([
        {
          title: '公司',
          key: 'companyName',
          dataIndex: 'companyName',
          width: 150,
        },
        {
          title: '仓库名称',
          key: 'warehouseName',
          dataIndex: 'warehouseName',
          width: 150,
        },
        {
          title: '物料大类',
          key: 'majorCategory',
          dataIndex: 'majorCategory',
          width: 150,
        },
        {
          title: '物料中类',
          key: 'middleCategory',
          dataIndex: 'middleCategory',
          width: 200,
        },

        {
          title: '物料小类',
          key: 'subCategory',
          dataIndex: 'subCategory',
          width: 200,
        },
        {
          title: '物料编号',
          key: 'materialCode',
          dataIndex: 'meterialCode',
          width: 150,
        },
        {
          title: '物料名称',
          key: 'materialName',
          dataIndex: 'meterialName',
          width: 200,
        },

        {
          title: '规格',
          key: 'specification',
          dataIndex: 'specification',
          width: 200,
        },
        {
          title: '等级',
          key: 'grade',
          dataIndex: 'grade',
          width: 200,
        },
        {
          title: '单位',
          key: 'unit',
          dataIndex: 'unit',
          width: 200,
        },
        {
          title: '上期结存数量',
          key: 'previousNum',
          dataIndex: 'previousNum',
          width: 200,
        },
        {
          title: '本期采购入库数量',
          key: 'purchaseIn',
          dataIndex: 'purchaseIn',
          width: 200,
        },
        {
          title: '本期调拨入库数量',
          key: 'transferIn',
          dataIndex: 'transferIn',
          width: 200,
        },
        {
          title: '本期领料出库数量',
          key: 'materialOut',
          dataIndex: 'materialOut',
          width: 200,
        },
        {
          title: '本期调拨出库数量',
          key: 'transferOut',
          dataIndex: 'transferOut',
          width: 200,
        },
        {
          title: '本期结存数量',
          key: 'totalNum',
          dataIndex: 'totalNum',
          width: 200,
        },
      ])

      let tc: any[] = tableColumns.map((o) => {
        let obj = {
          headerName: o.title,
          field: o.key,
          pinned: o['fixed'],
          tooltipField: o.key,
        }
        return obj
      })

      let a = [
        {
          showRowGroup: 'hide_def',
          headerName: '',
          checkboxSelection: true,
          headerCheckboxSelection: true,
          pinned: 'left',
          width: 50,
          resizable: false,
          filter: false,
          sortable: false,
          minWidth: 50,
          maxWidth: 50,
          lockPosition: 'left',
        },
      ]
      tc = a.concat(tc)
      const pageData = reactive<{
        warehouseId: any
        firmId: any
        pageLoading: any
        btnList: any[]
        majorCategory: any
        middleCategory: any
        subCategory: any
        bigList: any[]
        middleList: any[]
        smallList: any[]
        materialCode: any
        materialName: any
      }>({
        warehouseId: null,
        firmId: null,
        pageLoading: false,
        btnList: [],
        majorCategory: '',
        middleCategory: '',
        subCategory: '',
        bigList: [],
        middleList: [],
        smallList: [],
        materialCode: '',
        materialName: '',
      })

      onMounted(() => {
        // 切换tap到本页面执行的方法
        emitter.on('HardwareWarehouseMonthReport', () => {
          // selCxAll1({});
          doRefresh()
        })
      })
      //查询
      const selectHandler = () => {
        pagination.page = 1
        doRefresh()
      }
      // 表格准备事件
      const gridOption = ref()
      const gridReady = (params: any) => {
        gridOption.value = params.api
      }
      //导出
      const exports = () => {
        post({
          url: '/wms/ironwareStockSummary/exportIronwareStockDaily',
          data: {
            firmId: pageData.firmId,
            warehouseId: pageData.warehouseId,
            majorCategory: pageData.majorCategory,
            middleCategory: pageData.middleCategory,
            subCategory: pageData.subCategory,
            materialCode: pageData.materialCode,
            materialName: pageData.materialName,
          },
          responseType: 'blob',
        }).then((res: any) => {
          filedownload(res, '五金进销存.xlsx')
        })
      }
      //设置权限
      // ['查询', '新增', '删除', '导出', '导入']
      const permissionStore = usePermission()

      // if (permissionStore.hasPermisson('ppzl.cx')) {
      // }
      pageData.btnList.push('查询')

      pageData.btnList.push('导出')
      // if (permissionStore.hasPermisson('ppzl.dc')) {
      // }
      // if (permissionStore.hasPermisson('ppzl.dr')) {
      //   pageData.btnList.push('返回主页')
      // }
      const handleChange = (_data: any) => {
        table.handleSuccess(_data)
      }
      const defaultColDef = {
        sortable: true,
        resizable: true,
        filter: true,
      }
      const localeText1: any = ref(localeText)
      const huiche = () => {
        doRefresh()
      }
      const fhzy = () => {
        emit('takebiaoji', 0)
      }
      const pagingList1: any = ref(pagingList)
      const whService = new WHService()
      const fhWhList: any = whService.whList
      const configCascader = ref<{}>({
        corporateWidth: '189px', //公司宽度
        sectorWidth: '180px', //部门宽度
        corporateRquired: true, //公司是否必填
        sectorRquired: false, //部门是否必填
        size: 'mini', //选择框大小'mini' | 'small' | 'medium' | 'large'
        corporateName: '选择工厂', //公司label
        sectorName: '选择部门', //部门label
        cascaderShow: 'sector', //配置部门不显示
        corporateNameLabelWidth: '80px',
      })
      const firmChange = (data: any) => {
        // const { corporateId, sectorId, sectorLabel, corporateLabel } = data
        // pageData.dropDownData = corporateId
        const { corporateId } = data
        pageData.warehouseId = ''
        pageData.firmId = corporateId
        whService.getWarhouseListByFirmId(corporateId, '五金仓')
      }

      //下拉框  物料
      const WLfocusSel = (val: any) => {
        if (val === 1) {
          post({
            url: 'purchase/MaterialBigClass/getFieldValue',
            data: { bigClassName: '' },
          }).then(({ data, code }: any) => {
            if (code === 200) {
              pageData.bigList = data
            } else {
              Message.error({
                content: '查询失败！',
                duration: 5000,
              })
            }
          })
        } else if (val === 2) {
          post({
            // url: 'purchase/MaterialMiddleClass/getList',
            // data: {
            //   bigClassId: pageData.bigList.find(
            //     (item: any) => item.bigClassName === pageData.majorCategory
            //   )?.id,
            // },
            url: 'purchase/MaterialMiddleClass/getFieldValue',
            data: {
              middleClassName: '',
              filterMap: {
                bigClassId: pageData.bigList.find(
                  (item: any) => item.bigClassName === pageData.majorCategory
                )?.id,
              },
            },
          }).then(({ data, code }: any) => {
            if (code === 200) {
              pageData.middleList = data
            } else {
              Message.error({
                content: '查询失败！',
                duration: 5000,
              })
            }
          })
        } else if (val === 3) {
          post({
            url: 'purchase/MaterialSubClass/getFieldValueFilter',
            // data: {
            //   middleClassId: pageData.middleList.find(
            //     (item: any) => item.middleClassName === pageData.middleCategory
            //   )?.id,
            // },
            data: {
              subClassName: '',
              filterMap: {
                middleClassId: pageData.middleList.find(
                  (item: any) => item.middleClassName === pageData.middleCategory
                )?.id,
              },
            },
          }).then(({ data, code }: any) => {
            if (code === 200) {
              pageData.smallList = data
            } else {
              Message.error({
                content: '查询失败！',
                duration: 5000,
              })
            }
          })
        }
      }

      const bigChange = (val: any) => {
        if (val === 1) {
          pageData.middleList = []
          pageData.middleCategory = ''
          pageData.smallList = []
          pageData.subCategory = ''
        } else if (val === 2) {
          pageData.smallList = []
          pageData.subCategory = ''
        }
      }
      return {
        WLfocusSel,
        bigChange,
        fhWhList,
        configCascader,
        firmChange,
        pagingList1,
        huiche,
        localeText1,
        defaultColDef,
        tc,
        total,
        PageSize,
        change1,
        page,
        size,
        pagination,
        tableColumns,
        table,
        rowKey,
        pageData,
        selectHandler,
        exports,
        headerShow,
        handleChange,
        gridReady,
        fhzy,
      }
    },
    props: {
      biaoji: Number,
    },
    components: { Toolbar, PageTabelLayout, CorporateSectorCascader },
  }
</script>
<style scoped>
  :deep(.ag-cell-value) {
    user-select: initial;
    -moz-user-select: text;
    -ms-user-select: text;
    -webkit-user-select: text;
  }

  :deep(.ag-cell) {
    border-right: 1px solid #dde2eb;
  }

  :deep(.ag-header-cell) {
    border-right: 1px solid #dde2eb;
  }
</style>
